package view;

import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");

        //1.从请求中读取出用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username==null||"".equals(username)||password==null||"".equals(password)){
            String html = "<h3>用户名或密码缺少</h3>";
            resp.getWriter().write(html);
            return;
        }

        //2.从数据库中根据用户名查询密码
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if(user==null){
            String html = "<h3>用户名或密码错误</h3>";
            resp.getWriter().write(html);
            return;
        }

        //3.和数据库里的密码进行比较
        if(!user.getPassword().equals(password)){
            String html = "<h3>用户名或密码错误</h3>";
            resp.getWriter().write(html);
            return;
        }

        //4.登录成功，把当前的user对象存到HttpSession中
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);

        //5.登陆成功，跳转页面
        resp.sendRedirect("blog_list.html");
    }
}
